package com.sakura.mybatis.version4.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.sakura.mybatis.version3.utils.SqlSessionUtils;
import com.sakura.mybatis.version4.excel.dto.SysAgentDTO;
import com.sakura.mybatis.version4.mapper.SysAgentApplyMapper;
import com.sakura.mybatis.version4.mapper.SysAgentCertificationMapper;
import com.sakura.mybatis.version4.mapper.SysAgentMapper;
import com.sakura.mybatis.version4.pojo.SysAgent;
import com.sakura.mybatis.version4.pojo.SysAgentApply;
import com.sakura.mybatis.version4.pojo.SysAgentCertification;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author Sakura
 * @Date 2023/12/21 14:51
 * @Version 1.0
 */
public class BankInfoListener extends AnalysisEventListener<SysAgentDTO> {


    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 500;

    private static int count = 0;

    final String pathName = "config/mybatis/version4/mybatis-config.xml";

    private List<SysAgentDTO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    //没有匹配到的信息
    private List<String> list=new ArrayList<>();
    private List<String> existList=new ArrayList<>();

    @Override
    public void invoke(SysAgentDTO sysAgentDTO, AnalysisContext analysisContext) {
        if(StrUtil.isNotBlank(sysAgentDTO.getAgentCode())){
            cachedDataList.add(sysAgentDTO);
        }


        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        SqlSession sqlSession = null;
        try {
            sqlSession = SqlSessionUtils.getSqlSession(pathName, false);
            SysAgentMapper mapper = sqlSession.getMapper(SysAgentMapper.class);
            SysAgentCertificationMapper mapper1 = sqlSession.getMapper(SysAgentCertificationMapper.class);
            SysAgentApplyMapper sysAgentApplyMapper = sqlSession.getMapper(SysAgentApplyMapper.class);
            cachedDataList.stream().forEach(m -> {
                SysAgent sysAgent = new SysAgent();
                sysAgent.setAgentCode(m.getAgentCode());

                List<SysAgent> sysAgents = mapper.queryAllByLimit(sysAgent);

                if (CollectionUtil.isNotEmpty(sysAgents)) {
                    SysAgent mySysagent = sysAgents.get(0);
                    mySysagent.setBankNo(m.getBankNo());
                    mySysagent.setBankAccountNumber(m.getBankAccountNumber());
                    mySysagent.setOpeningBank(m.getOpeningBank());
                    if (StrUtil.isNotBlank(m.getDegree())) {
                        mySysagent.setAgentDegree(m.getDegree());
                    }
                    mapper.update(mySysagent);

                    //增加额外信息
                    SysAgentCertification sysAgentCertification=new SysAgentCertification();
                    sysAgentCertification.setAgentId(mySysagent.getId());
                    sysAgentCertification.setCreatedDate(new Date());
                    sysAgentCertification.setResult("2");
                    sysAgentCertification.setCertificationResult("Y");
                    mapper1.insert(sysAgentCertification);


                    //注册信息
                    SysAgentApply sysAgentApply=new SysAgentApply();
                    sysAgentApply.setAgentCode(mySysagent.getAgentCode());
                    sysAgentApply.setReviewStatus(4);//审核通过
                    sysAgentApply.setReviewRemark("个代导入数据");
                    sysAgentApply.setDegreeLostFlag("0");
                    sysAgentApply.setAliBusinessNo(mySysagent.getAgentCode());
                    sysAgentApply.setCreatedUser(DateUtil.today());
                    sysAgentApply.setCreatedDate(new Date());
                    sysAgentApply.setModifiedDate(new Date());
                    sysAgentApply.setIsDelete(0);
                    sysAgentApplyMapper.insert(sysAgentApply);

                } else {
                    list.add(m.getAgentCode());
                }
            });

            sqlSession.commit();
            sqlSession.clearCache();
            //统计数据量
            count += cachedDataList.size();
            System.out.println(String.format("【%s】期银行数据已读取【%s】条数据,【%s】条已修改,【%s】条未匹配到账号信息!", DateUtil.today(), count, count - list.size(), list.size()));
            System.out.println("未匹配账号【"+list.size()+"】条数据:"+ JSON.toJSONString(list));
        } catch (Exception e) {
            count -= cachedDataList.size();
            if (null != sqlSession) {
                sqlSession.rollback();
            }
            System.out.println(String.format("【%s】期银行数据导入失败!异常原因:%s", DateUtil.today(), e.getMessage()));
        } finally {
            if (null != sqlSession) {
                sqlSession.close();
            }
        }


    }
}
